var express = require("express");
var router = express.Router();
const bcrypt = require("bcrypt");
const dayjs = require("dayjs");

const { getResult, getList } = require("../utils/sql");
const { createToken } = require("../utils/jwt");

router.post("/register", async function (req, res) {
  let { name, account, password, color } = req.body;
  if (name.length > 8) {
    res.send({
      code: 500,
      message: "name is too long",
    });
    return;
  }
  let result = await getList("user", ["name"], [name]);
  if (result && result.length !== 0) {
    res.send({
      code: 500,
      message: "name Already Exist",
    });
    return;
  }
  let result1 = await getList("user", ["account"], [account]);
  if (result1 && result1.length !== 0) {
    res.send({
      code: 500,
      message: "account Already Exist",
    });
    return;
  }
  bcrypt.hash(password, 10, async (err, hash) => {
    if (err) {
      res.status(500).send({
        error: "Unknown Error",
      });
      return;
    }
    let sql = `INSERT INTO user (account,name,password,color) value(?,?,?,?)`;
    let paramsList = [account, name, hash, color];
    await getResult({
      sql,
      paramsList,
    });
    res.send({
      code: 0,
      message: "register Successfully",
    });
  });
});

router.post("/login", async function (req, res) {
  let { name, password } = req.body;
  // 根据name去找到userId
  let result = await getResult({
    sql: "SELECT * FROM user WHERE name=? OR account=?",
    paramsList: [name, name],
  });
  if (result[0] && result[0].length !== 0) {
    const sotredHash = result[0][0].password;
    bcrypt.compare(password, sotredHash, (err, compareRes) => {
      if (err) {
        console.log(err);
        res.status(500).send({
          code: 500,
          error: "Unknown Error",
        });
      } else {
        if (compareRes) {
          console.log(result[0][0].user_id, "=========71");
          let token = createToken(result[0][0].user_id);
          console.log(token);
          res.send({
            code: 0,
            data: {
              name: result[0][0].name,
              token,
              color: result[0][0].color,
              userId: result[0][0].user_id,
            },
            message: "OK",
          });
        } else {
          res.send({
            code: 500,
            message: "password Error",
          });
        }
      }
    });
  } else {
    res.send({
      code: 400,
      message: "no User",
    });
  }
});

router.put("/update", async function (req, res) {
  if (!req.headers.authorization) {
    res.send({
      code: 40001,
      message: "no Login",
    });
    return;
  }
  let userId = req.headers.authorization;
  let { oldPassWord, password, color } = req.body;
  let result = await getList("user", ["user_id"], [userId]);
  if (result && result[0].length !== 0) {
    bcrypt.compare(oldPassWord, result[0].password, function (err, isMatch) {
      console.log(result[0].password, "===", oldPassWord);
      if (err) {
        res.status(500).send({
          error: "Unknown Error",
        });
        return;
      } else if (isMatch) {
        bcrypt.hash(password, 10, async (err, hash) => {
          if (err) {
            res.status(500).send({
              error: "Unknown Error",
            });
            return;
          }
          let sql = `UPDATE user SET password=?, color=? WHERE user_id=?`;
          let paramsList = [hash, color, userId];
          await getResult({
            sql,
            paramsList,
          });
          res.send({
            code: 0,
            message: "update Successfully",
          });
        });
      } else {
        res.send({
          code: 500,
          message: "oldPassWord match fail",
        });
      }
    });
  }
});

router.get("/user", async function (req, res) {
  let result = await getList("user");

  res.send({
    code: 0,
    data: result,
    message: "OK",
  });
});

router.get("/system/info", async function (req, res) {
  let userSql = `SELECT COUNT(*) AS total_count FROM user`;
  let dailySql = `SELECT COUNT(*) AS total_count FROM daily_task`;
  let yeaylySql = `SELECT COUNT(*) AS total_count FROM yearly_plan`;
  let result = await getResult({ sql: userSql, paramsList: [] });
  let result1 = await getResult({ sql: dailySql, paramsList: [] });
  let result2 = await getResult({ sql: yeaylySql, paramsList: [] });
  console.log(result[0], result1[0], result2[0]);
  res.send({
    code: 0,
    data: {
      userTotal: result[0][0].total_count,
      dailyTotal: result1[0][0].total_count,
      yearlyTotal: result2[0][0].total_count,
    },
    message: "OK",
  });
});

router.get("/sql/test", async function (req, res) {
  // let sql = `SELECT color,account FROM user`;
  // let sql = `INSERT INTO user (account,name,password) value(?,?,?)`;
  // let sql = `UPDATE user SET name=? WHERE account LIKE ?`;
  // let sql = `DELETE FROM user WHERE account=?`;
  // let sql = `
  // SELECT * FROM daily_task
  // ORDER BY create_time DESC
  // LIMIT ? OFFSET ?
  // `;
  // 联表查询 查询create_time在4-20号之后的数据

  // 存在性检查 result[0][0].exist -> 1为存在 0 为不存在
  // let sql = `SELECT EXISTS(SELECT * FROM user WHERE account=?) as exist`;

  // 查询yearly_plan中所有数据的goal
  //  daily_task date为2025-01-02的content
  //  weekly_task中user_id为2的task
  // 返回的字段名是goal
  let sql = `
  SELECT
    yearly_plan.goal
  FROM yearly_plan

  UNION ALL
  SELECT
    daily_task.status AS goal
  FROM
    daily_task
  WHERE
    date=?
  UNION ALL
  SELECT
    weekly_task.task
  FROM
    weekly_task
  WHERE
    user_id=?
`;
  let paramsList = ["2025-01-02", "2"];

  let result = await getResult({ sql, paramsList });
  // result[0].forEach((item) => {
  //   item.create_time = new Date(item.create_time);
  // });
  if (result.message) {
    res.send({
      code: 500,
      message: result.message,
    });
    return;
  }
  console.log(result, "====182");

  res.send({
    code: 0,
    data: result[0],
    message: "OK",
  });
});

module.exports = router;
